package com.jiantong.web.open.app.work;

import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.web.core.enums.ExceptionCode;
import com.jiantong.work.model.VaccinePurchaseRecord;
import com.jiantong.work.service.VaccinePurchaseRecordReadService;
import com.jiantong.work.service.VaccinePurchaseRecordWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Strings;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * 疫苗记录
 * Created by maowenjie on 2017/4/17.
 */
@Slf4j
@OpenBean
public class VaccinePurchaseRecordApis {
    @RpcConsumer
    private VaccinePurchaseRecordReadService vaccinePurchaseRecordReadService;

    @RpcConsumer
    private VaccinePurchaseRecordWriteService vaccinePurchaseRecordWriteService;

    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;

    /**
     * find by id
     * @param id
     * @return
     */
    @OpenMethod(
            key = "find.vaccine.purchase.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public VaccinePurchaseRecord findById(Long id){
        if (id==null){
            log.error("is should be not null");
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"is should be not null");
        }
        Response<VaccinePurchaseRecord> response = vaccinePurchaseRecordReadService.findById(id);
        if(!response.isSuccess()){
            log.error("failed to find vaccinePurchaseRecord , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 根据status分页查询
     * @param pageNo
     * @param pageSize
     * @param breedFactoryId
     * @param status
     * @return
     */
    @OpenMethod(
            key = "paging.vaccine.purchase",
            paramNames = {"pageNo","pageSize", "breedFactoryId","status"},
            httpMethods = RequestMethod.GET
    )
    public Paging<VaccinePurchaseRecord> pagingVaccinePurchaseRecord(Integer pageNo, Integer pageSize,Long breedFactoryId, Integer status){
        if (breedFactoryId == null){
            log.error("breedFactoryId is should be not null");
            throw new OPClientException(ExceptionCode.PARAMETER_NOT_EXIST.value(),"breedFactoryId is should be not null");
        }
        Response<Paging<VaccinePurchaseRecord>> response = vaccinePurchaseRecordReadService.pagingVaccinePurchaseRecord(pageNo,pageSize,breedFactoryId,status);
        if(!response.isSuccess()){
            log.error("failed to paging vaccinePurchaseRecord farm , cause : {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 创建疫苗记录 根据toStatus
     * @param vaccinePurchaseRecord
     * @param toStatus
     * @return
     */
    @OpenMethod(
            key = "create.vaccine.purchase",
            paramNames = {"vaccinePurchase","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Map<String , Object> createVaccinePurchaseRecord(VaccinePurchaseRecord vaccinePurchaseRecord , Integer toStatus){
/*        LoginUser loginUser = UserUtil.getCurrentUser();
        BreedFactory breedFactory = breedFactoryReadService.findById(loginUser.getOrganizationId()).getResult();
        if(breedFactory.getIsScale() != 1){
            log.error("this is san hu");
            throw new OPClientException("this is san hu");
        }*/
        Response<Map<String , Object>> response = vaccinePurchaseRecordWriteService.createVaccinePurchaseRecord(vaccinePurchaseRecord,toStatus);
        if(!response.isSuccess()){
            log.error("failed to create vaccinePurchaseRecord, cause : {}",vaccinePurchaseRecord,toStatus,response.getError());
            throw new OPServerException(ExceptionCode.DATA_WRITE_FAIL.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 更新疫苗记录
     * @param vaccinePurchaseRecord
     * @param toStatus
     * @return
     */
    @OpenMethod(
            key = "update.vaccine.purchase",
            paramNames = {"vaccinePurchase","toStatus"},
            httpMethods = RequestMethod.PUT
    )
    public  Map<String , Object> updateVaccinePurchaseRecord(VaccinePurchaseRecord vaccinePurchaseRecord , Integer toStatus){
        if(vaccinePurchaseRecord.getId() == null){
            log.error("failed to update quarantineCenterHarmless error = {}, cause : {}", vaccinePurchaseRecord,vaccinePurchaseRecord.getId());
            throw new OPClientException(ExceptionCode.ID_NOT_EXIST.value(),"quarantineCenterHarmless.id.is.null");
        }

        Response<Map<String , Object>> statusResponse = vaccinePurchaseRecordReadService.findStatusById(vaccinePurchaseRecord.getId());
        if(statusResponse.isSuccess() && !statusResponse.getResult().get("status").equals(vaccinePurchaseRecord.getStatus())){
            log.error("vaccinePurchaseRecord is already submitted error = {}, cause : {}", vaccinePurchaseRecord.getStatus(),statusResponse.getResult().get("status"));
            throw new OPClientException(ExceptionCode.DATA_NOT_FOUND.value(),"this.report.is.already.submitted");
        }

        Response<Map<String , Object>> response = vaccinePurchaseRecordWriteService.updateVaccinePurchaseRecord(vaccinePurchaseRecord,toStatus);
        if(!response.isSuccess()){
            log.error("failed to update vaccinePurchaseRecord error = {}, cause : {}", vaccinePurchaseRecord, response.getError());
            throw new OPServerException(ExceptionCode.DATA_UPDATE_FAIL.value(),response.getError());
        }
        return response.getResult();
    }

    /**
     * 根据场名和指定时间段分页查询
     * @param pageNo 查看的页数
     * @param pageSize 每页的长度
     * @param breedFactoryId 场名
     * @param fromDate 开始时间
     * @param toDate 到达时间
     * @return Paging<疫苗记录>
     */
    @OpenMethod(
            key = "paging.status.vaccine.purchase",
            paramNames = {"pageNo", "pageSize", "breedFactoryId","breedType", "fromDate", "toDate"},
            httpMethods = RequestMethod.GET)
    public Paging<VaccinePurchaseRecord> pagingVaccinePurchaseRecord(Integer pageNo,
                                                                           Integer pageSize,
                                                                           Long breedFactoryId,
                                                                     Integer breedType,
                                                                           String fromDate,
                                                                           String toDate) {
        Date start = null;
        if (!Strings.isNullOrEmpty(fromDate)) {
            start = DateTime.parse(fromDate).toDate();
        }

        Date end = null;
        if (!Strings.isNullOrEmpty(toDate)) {
            end = DateTime.parse(toDate).toDate();
        }
        Response<Paging<VaccinePurchaseRecord>> resp = vaccinePurchaseRecordReadService
                .pagingVaccinePurchaseRecordGqv(pageNo, pageSize, breedFactoryId,breedType, start, end);
        if (!resp.isSuccess()) {
            log.error("failed to paging vaccine purchase{}, cause : {}", resp.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),resp.getError());
        }
        return resp.getResult();
    }
}
